<?php

namespace app\company\controller\user\list;

use app\admin\service\ConfigService;
use app\admin\service\UserExportService;
use app\admin\service\UserImportService;
use app\admin\service\UserService;
use app\BaseController;
use app\model\ConsultTimeModel;
use app\model\DepartmentAdminModel;
use app\model\DepartmentModel;
use app\model\RoleModel;
use app\model\UnitModel;
use app\model\UserModel;
use app\model\UserTagModel;
use think\App;

class UserList extends BaseController
{
    protected $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new UserModel();
    }

    /**
     * 下载模板
     * @return false|string
     */
    public function downloadTemplate(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位' => 'require|integer|>:0',
                'type|类型' => 'require',
            ]);
            if ($param['type'] == 1) {
                $ConfigService = new ConfigService($this->app);
                $config = $ConfigService->getConfig($param['unit_id'], 'department_management');
                if ($config['type'] == 1) {
                    $url = '/template/user.xlsx';
                } else {
                    $url = '/template/school_user.xlsx';
                }
            } elseif ($param['type'] == 2) {
                $url = '/template/consultant.xlsx';
            } elseif ($param['type'] == 3) {
                $url = '/template/admin.xlsx';
            } else {
                return error('参数错误！');
            }
            return success(['url' => $url]);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 角色选择器
     * @return false|string
     */
    public function roleSelector(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位' => 'require|integer|>:0',
            ]);
            $RoleModel = new RoleModel();
            $data = $RoleModel->field('id,name,mode')
                ->where('unit_id', '=', $param['unit_id'])->select()->toArray();
            $UnitModel = new UnitModel();
            return success([
                'data' => $data,
                'unit' => $UnitModel->where('id', '=', $param['unit_id'])->field('id,name,level,province_id,city_id,area_id,province_name,city_name,area_name')->find(),
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 普通用户列表
     * @return false|string
     */
    public function userList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'role_id|角色' => 'require|integer|>:0',
                'unit_id|单位' => 'require|integer|>:0',
                'pageSize|每页数量' => 'require|integer|>:0',
            ]);
            $where = [];
            if (!empty($param['role_id'])) {
                $where[] = ['role_id', '=', $param['role_id']];
            }
            if (!empty($param['status'])) {
                $where[] = ['status', '=', $param['status']];
            }
            if (!empty($param['name'])) {
                $where[] = ['name|username', 'like', '%' . $param['name'] . '%'];
            }
            if (isset($param['sex']) && strlen($param['sex']) > 0) {
                $where[] = ['sex', '=', $param['sex']];
            }
            if (isset($param['student_status']) && strlen($param['student_status']) > 0) {
                $where[] = ['student_status', '=', $param['student_status']];
            }
            if (isset($param['department_id']) && strlen($param['department_id']) > 0) {
                $where[] = ['department_id', '=', $param['department_id']];
            }
            if (!empty($param['department_admin_id'])) {
                $DepartmentAdminModel = new DepartmentAdminModel();
                $department_ids = $DepartmentAdminModel->where('uid', '=', $param['department_admin_id'])->column('department_id');
                if (count($department_ids) > 0) {
                    $where[] = ['department_id', 'in', $department_ids];
                } else {
                    $where[] = ['department_id', '=', '-1'];
                }
            }
            $where[] = ['role_mode', '=', 3];
            $where[] = ['unit_id', '=', $param['unit_id']];
            $query = $this->mode->where($where);
            $data = $query->paginate($param['pageSize'])->toArray();
            if (count($data['data']) > 0) {
                $UserService = new UserService($this->app);
                $DepartmentAffiliationAll = $UserService->getDepartmentAffiliationAll($param['unit_id']);
                $department_ids = array_column($data['data'], 'department_id');
                $DepartmentAdminAll = $UserService->getDepartmentAdminAll($department_ids);
                foreach ($data['data'] as &$item) {
                    //部门归属
                    $item['ascription_name'] = $DepartmentAffiliationAll[$item['department_id']]['ascription_name'] ?? '';
                    //所在部门
                    $item['department_name'] = $DepartmentAffiliationAll[$item['department_id']]['all_name'] ?? '';
                    //部门number（班级编号）
                    $item['department_number'] = $DepartmentAffiliationAll[$item['department_id']]['number'] ?? '';
                    //部门管理员
                    $item['department_admin'] = $DepartmentAdminAll[$item['department_id']]['user_name'] ?? '';
                }
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 咨询师列表
     * @return false|string
     */
    public function consultantList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'role_id|角色' => 'require|integer|>:0',
                'unit_id|单位' => 'require|integer|>:0',
                'pageSize|每页数量' => 'require|integer|>:0',
            ]);
            $where = [];
            if (!empty($param['role_id'])) {
                $where[] = ['role_id', '=', $param['role_id']];
            }
            if (!empty($param['name'])) {
                $where[] = ['name|username', 'like', '%' . $param['name'] . '%'];
            }
            if (isset($param['is_scheduling']) && strlen($param['is_scheduling']) > 0) {
                $where[] = ['is_scheduling', '=', $param['is_scheduling']];
            }
            if (isset($param['sex']) && strlen($param['sex']) > 0) {
                $where[] = ['sex', '=', $param['sex']];
            }
            if (isset($param['tag_id']) && strlen($param['tag_id']) > 0) {
                $UserTagModel = new UserTagModel();
                $uids = $UserTagModel->where('tag_id', '=', $param['tag_id'])->column('uid');
                if (count($uids) > 0) {
                    $where[] = ['id', 'in', $uids];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            $where[] = ['role_mode', '=', 2];
            $where[] = ['unit_id', '=', $param['unit_id']];
            $query = $this->mode->where($where);
            $data = $query->with([
                'unitName',
                'userTag' => function ($queue) {
                    $queue->with(['tag']);
                }
            ])->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as $key => &$item) {
                //服务对象
                $ConsultTimeModel = new ConsultTimeModel();
                $department_id = $ConsultTimeModel->where([
                    ['consult_id', '=', $item['id']],
                    ['start_time', '>', time()]
                ])->order('time desc')->with(['departmentName'])->field('model,department_id,time')->find();
                if ($department_id != null) {
                    if ($department_id['department_id'] == 0) {
                        $ServerObject = '服务所有部门';
                        //排班服务类型
                        $ServerType = '所有部门';
                    } else {
                        $ServerObject = '服务指定部门';
                        //排班服务类型
                        $ServerType = $department_id['department_name'];
                    }
                    //排班情况
                    $ConsultDate = $ConsultTimeModel->where([
                        ['consult_id', '=', $item['id']],
                        ['start_time', '>', time()]
                    ])->distinct(true)->column('date');
                    $day = count($ConsultDate);
                    $item['scheduling_day'] = $day ? '已排班' : '未排班'; //排班情况
                    $item['scheduling_day_num'] = $day ? $day . '天' : '--'; //排班情况
                    $item['service_object'] = $ServerObject;//服务对象 [指定部门或者所有部门]
                    $item['service_type'] = $ServerType;//服务类型
                } else {
                    $item['scheduling_day'] = '未排班'; //排班情况
                    $item['scheduling_day_num'] = '--'; //排班天数
                    $item['service_object'] = '--';//服务对象 [指定部门或者所有部门]
                    $item['service_type'] = '--';//服务类型
                }
            }
            $data['ids'] = $query->column('id');
            $data['data'] = array_values($data['data']);
            $data['total'] = count($data['data']);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 管理员列表
     * @return false|string
     */
    public function adminList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'role_id|角色' => 'require|integer|>:0',
                'unit_id|单位' => 'require|integer|>:0',
                'pageSize|每页数量' => 'require|integer|>:0',
            ]);
            $where = [];
            if (!empty($param['role_id'])) {
                $where[] = ['role_id', '=', $param['role_id']];
            }
            if (!empty($param['name'])) {
                $where[] = ['name|username', 'like', '%' . $param['name'] . '%'];
            }
            if (isset($param['sex']) && strlen($param['sex']) > 0) {
                $where[] = ['sex', '=', $param['sex']];
            }
            if (!empty($param['department_id'])) {
                $DepartmentAdminModel = new DepartmentAdminModel();
                $uids = $DepartmentAdminModel->where('department_id', '=', $param['department_id'])->group('uid')->column('uid');
                if (count($uids) > 0) {
                    $where[] = ['id', 'in', $uids];
                } else {
                    $where[] = ['id', '=', '-1'];
                }
            }
            if (!empty($param['level'])) {
                $DepartmentModel = new DepartmentModel();
                $uids = $DepartmentModel->where('level', '=', $param['level'])
                    ->with(['departmentAdmins' => function ($query) {
                        $query->field('id,uid,department_id');
                    }])
                    ->field('id')->select();
                if (count($uids) > 0) {
                    $ids = [];
                    foreach ($uids as $item) {
                        if (!empty($item['departmentAdmins'])) {
                            foreach ($item['departmentAdmins'] as $v) {
                                $ids[] = $v['uid'];
                            }
                        }
                    }
                    $where[] = ['id', 'in', array_unique($ids)];
                } else {
                    $where[] = ['id', '=', '-1'];
                }
            }
            $where[] = ['role_mode', '=', 1];
            $where[] = ['unit_id', '=', $param['unit_id']];
            $query = $this->mode->where($where);
            $data = $query->with([
                'unitName',
                'DepartmentAdmins' => function ($queue) {
                    $queue->with(['Department']);
                }
            ])->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item) {
                if (empty($item['DepartmentAdmins'])) {
                    $item['level_name'] = '0级管理员';
                } else {
                    $department_level = min(array_column($item['DepartmentAdmins'], 'department_level'));
                    $item['level_name'] = $department_level . '级管理员';
                }
                $item['admin_department'] = '';
                foreach ($item['DepartmentAdmins'] as $v) {
                    if (empty($item['admin_department'])) {
                        $item['admin_department'] = $v['department_name'] ?? '';
                    } else {
                        $item['admin_department'] .= '、' . $v['department_name'] ?? '';
                    }
                }
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 超级管理员列表
     * @return bool|string
     */
    public function SuperAdminList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位' => 'require|integer|>:0',
                'pageSize|每页数量' => 'require|integer|>:0',
            ]);
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name|username', 'like', '%' . $param['name'] . '%'];
            }
            if (isset($param['sex']) && strlen($param['sex']) > 0) {
                $where[] = ['sex', '=', $param['sex']];
            }
            $where[] = ['role_id', '=', 0];
            $where[] = ['unit_id', '=', $param['unit_id']];
            $query = $this->mode->where($where);
            $data = $query->with([
                'unitName'
            ])->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 超级管理员-添加
     * @return bool|string
     */
    public function SuperAdminAdd(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位ID' => 'require|integer|>:0',
                'username|账号' => 'require|length:8,18|alphaNum',
                'password|密码' => 'require|length:8,18',
                'name|姓名' => 'require',
//                'sex|性别' => 'require'
            ]);
            $UnitModel = new UnitModel();
            $UserModel = new UserModel();
            $uid = $UserModel->where('username', '=', $param['username'])->value('id');
            if ($uid) throw new \Exception('账号已存在！');
            $UnitInfo = $UnitModel->where('id', '=', $param['unit_id'])->find();
            if (!$UnitInfo) throw new \Exception('参数错误！');
            $param['company_id'] = $UnitInfo['company_id'];
            $param['areas_id'] = $UnitInfo['areas_id'];
            $param['type'] = 3;
            $param['password'] = encrypt_password($param['password']);
            $param['avatar'] = '/user_avatar/admin.png';
            $param['level'] = $UnitInfo['level'];
            $param['province_id'] = $UnitInfo['province_id'];
            $param['city_id'] = $UnitInfo['city_id'];
            $param['area_id'] = $UnitInfo['area_id'];
            $param['province_name'] = $UnitInfo['province_name'];
            $param['city_name'] = $UnitInfo['city_name'];
            $param['area_name'] = $UnitInfo['area_name'];
            $param['time'] = time();
            $UserModel->insert($param);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 禁止登录
     * @return false|string
     */
    public function prohibitLogin(): bool|string
    {
        try {
            $id = $this->request->post('id');
            $status = $this->request->post('status');
            if (is_array($id)) {
                $this->mode->where('id', 'in', $id)->update([
                    'status' => $status
                ]);
            } else {
                $this->mode->where('id', '=', $id)->update([
                    'status' => $status
                ]);
            }
            return success([], '更新成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 添加账号
     * @return false|string
     */
    public function add(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位' => 'require|integer|>:0',
                'username|账号' => 'require|length:8,18|alphaNum',
                'password|密码' => 'require|length:8,18',
                'name|姓名' => 'require',
                'sex|性别' => 'require',
                'role_id|角色' => 'require',
            ]);
            $uid = $this->mode->where('username', '=', $param['username'])->value('id');
            if ($uid) throw new \Exception('账号已存在！');
            //验证当前是学院制，还是非学院制
            $ConfigService = new ConfigService($this->app);
            $config = $ConfigService->getConfig($param['unit_id'], 'department_management');
            if ($config['type'] == 2 && !empty($param['department_id'])) {
                //如果是学院制，选择的部门必须大于等于第三层级（班级）
                $department = new DepartmentModel();
                $level = $department->where('id', $param['department_id'])->value('level');
                if ($level <= 2) throw new \Exception('学院制新增用户必须选择第三级部门或者以下等级的部门！');
            }
            $RoleModel = new RoleModel();
            $UnitModel = new UnitModel();
            $RoleInfo = $RoleModel->where('id', '=', $param['role_id'])->find();
            $UnitInfo = $UnitModel->where('id', '=', $param['unit_id'])->find();
            if (!$RoleInfo || !$UnitInfo) throw new \Exception('参数错误！');
            $param['company_id'] = $UnitInfo['company_id'];
            $param['areas_id'] = $UnitInfo['areas_id'];
            $param['role_mode'] = $RoleInfo['mode'];
            $param['province_id'] = $UnitInfo['province_id'];
            $param['city_id'] = $UnitInfo['city_id'];
            $param['area_id'] = $UnitInfo['area_id'];
            $param['province_name'] = $UnitInfo['province_name'];
            $param['city_name'] = $UnitInfo['city_name'];
            $param['area_name'] = $UnitInfo['area_name'];
            $param['type'] = 4;
            $param['time'] = time();
            $param['password'] = encrypt_password($param['password']);
            if ($RoleInfo['mode'] < 3) $param['type'] = 3;
            if (empty($param['avatar'])) {
                $UserService = new UserService($this->app);
                switch ($RoleInfo['mode']) {
                    case 1:
                        $param['avatar'] = $UserService->getDefaultAvatar('admin');
                        break;
                    case 2:
                        if ($param['sex'] == 1) {
                            $param['avatar'] = $UserService->getDefaultAvatar('male_counselor');
                        } else {
                            $param['avatar'] = $UserService->getDefaultAvatar('female_counselor');
                        }
                        break;
                    default:
                        if ($param['sex'] == 1) {
                            $param['avatar'] = $UserService->getDefaultAvatar('male');
                        } else {
                            $param['avatar'] = $UserService->getDefaultAvatar('female');
                        }

                }
            }
            if (!empty($param['tag'])) {
                $tag = $param['tag'];
                unset($param['tag']);
                $uid = $this->mode->insertGetId($param);
                $tagData = [];
                foreach ($tag as $v) {
                    $tagData[] = [
                        'uid' => $uid,
                        'tag_id' => $v,
                        'time' => time()
                    ];
                }
                if (count($tagData) > 0) {
                    $UserTagModel = new UserTagModel();
                    $UserTagModel->insertAll($tagData);
                }
            } else {
                $this->mode->insert($param);
            }
            return success([], '添加成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑账号
     * @return false|string
     */
    public function update(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require|integer|>:0',
            ]);
            $info = $this->mode->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if (!empty($param['password'])) {
                if (!validatePassword($param['password'])) throw new \Exception('密码过于简单！');
                $param['password'] = encrypt_password($param['password']);
            }
            if (!empty($param['tag'])) {
                $tag = $param['tag'];
                unset($param['tag']);
                $tagData = [];
                foreach ($tag as $v) {
                    $tagData[] = [
                        'uid' => $param['id'],
                        'tag_id' => $v,
                        'time' => time()
                    ];
                }
                if (count($tagData) > 0) {
                    $UserTagModel = new UserTagModel();
                    $UserTagModel->where('uid', '=', $param['id'])->update([
                        'is_del' => 1,
                        'del_time' => time()
                    ]);
                    $UserTagModel->insertAll($tagData);
                }
            }
            $param = array_filter($param);
            $info->save($param);
            return success([], '更新成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 删除账号
     * @return false|string
     */
    public function del(): bool|string
    {
        $this->mode->startTrans();
        try {
            $id = $this->request->param('id');
            $DepartmentAdminModel = new DepartmentAdminModel();
            $ConsultTimeModel = new ConsultTimeModel();
            if (is_array($id)) {
                $this->mode->where('id', 'in', $id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
                $DepartmentAdminModel->where('uid', 'in', $id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
                $ConsultTimeModel->where('consult_id', 'in', $id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            } else {
                $this->mode->where('id', '=', $id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
                $DepartmentAdminModel->where('uid', '=', $id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
                $ConsultTimeModel->where('consult_id', '=', $id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            $this->mode->commit();
            return success([], '删除成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 导入用户
     * @return false|string
     */
    public function userImport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位' => 'require|integer|>:0',
                'role_id|角色' => 'require|integer|>:0',
            ]);
            $RoleModel = new RoleModel();
            $RoleInfo = $RoleModel->where('id', '=', $param['role_id'])->find();
            if (!$RoleInfo) throw new \Exception('参数错误！');
            $type = 3;
            if ($RoleInfo['mode'] == 3) {
                $type = 4;
            }
            $UserImportService = new UserImportService($this->app);
            if (!$UserImportService->import($param['file'], [
                'company_id' => $this->userData['company_id'],
                'areas_id' => $this->userData['areas_id'],
                'unit_id' => $param['unit_id'],
                'role_id' => $RoleInfo['id'],
                'role_mode' => $RoleInfo['mode'],
                'type' => $type,
                'province_id' => $this->userData['province_id'],
                'city_id' => $this->userData['city_id'],
                'area_id' => $this->userData['area_id'],
                'province_name' => $this->userData['province_name'],
                'city_name' => $this->userData['city_name'],
                'area_name' => $this->userData['area_name'],
            ])) throw new \Exception($UserImportService->message);
            return success([], '导入成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 批量导出普通用户
     * @return bool|string
     */
    public function UserExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'unit_id|单位' => 'require|integer|>:0',
            ]);
            if (!is_array($param['id'])) throw new \Exception('参数错误！');
            $UserExportService = new UserExportService($this->app);
            $data = $UserExportService->UserExport($param['id'], $param['unit_id']);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 批量导出咨询师
     * @return bool|string
     */
    public function ConsultExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'unit_id|单位' => 'require|integer|>:0',
            ]);
            if (!is_array($param['id'])) throw new \Exception('参数错误！');
            $UserExportService = new UserExportService($this->app);
            $data = $UserExportService->ConsultExport($param['id']);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 批量导出管理员
     * @return bool|string
     */
    public function AdminExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'unit_id|单位' => 'require|integer|>:0',
            ]);
            if (!is_array($param['id'])) throw new \Exception('参数错误！');
            $UserExportService = new UserExportService($this->app);
            $data = $UserExportService->AdminExport($param['id'],$param['unit_id']);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


}